package com.xcolud.redisdemo.services;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author songshiming
 * @date 2025/01/12
 * @des Redis HyperLogLog类型
 */

@Service
@Slf4j
public class HyperLogLogService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    // 将指定的元素添加到HyperLogLog中，可以添加多个元素
    public void pfAdd(String key, String... value) {
        redisTemplate.opsForHyperLogLog().add(key, value);
    }

    // 返回给定HyperLogLog的基数估算值。当一次统计多个HyperLogLog时
    // (通过key实现时间窗口统计user:web1:2020061600、user:web1:2020061601)，需要对多个HyperLogLog结构进行比较，并将并集的结果放入一个临时的HyperLogLog，性能不高，谨慎使用
    public Long pfCount(String... key) {
        return redisTemplate.opsForHyperLogLog().size(key);
    }

    // 将多个HyperLogLog进行合并，将并集的结果放入一个指定的HyperLogLog中
    public void pfMerge(String destKey, String... sourceKey) {
        redisTemplate.opsForHyperLogLog().union(destKey, sourceKey);
    }
}
